<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\InputGroup;
use App\Http\Requests\ItemRequest;
use view;
use App\Models\InputItem;

class ItemsController extends Controller
{

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(InputGroup $inputgroup)
    {
        $items = $inputgroup->items()->withCount('options')->get();
        return view('admin.items.index', ['datas' => $items, 'inputgroup' => $inputgroup]);
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(InputGroup $inputgroup)
    {
        return view('admin.items.create', ['inputgroup' => $inputgroup]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(ItemRequest $request, InputGroup $inputgroup)
    {
        $inputgroup->items()->create($request->all());
        return redirect()->route('admin.inputgroup.items.index', $inputgroup);
        
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(InputItem $item)
    {
        return view('admin.items.create', ['data' => $item, 'inputgroup' => $item->group]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, InputItem $item)
    {
        $item->update($request->input());
        return redirect()->route('admin.inputgroup.items.index', $item->group);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(InputItem $item)
    {
        if($item->options()->exists()) {
            return response()->json(['msg' => 'please delete  all options of the item'],400);
        }
        $item->delete();
        return response()->json(['success' => 'ok']);
    }
}
